// pages/login/wechatlogin.js
const app = getApp();
const db = wx.cloud.database();
const collection = db.collection('userinfo');
const _ = db.command;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasLogin: false,
    hasRegister: false,
    userInfo: {},
  },

  async getUserInfo(openid) {
    let userdata;
    try {
      userdata = (await collection.where({
        _id: openid,
      }).get()).data;
    } catch (err) {
      if (err.errCode == -502005) {
        // collection不存在，需要新建
        await this.createCollection();
      }
      return;
    }

    if (userdata.length == 0) {
      return;
    }
    return userdata[0];
  },

  nickNameConfirm(e) {
    console.debug(e)
    this.setData({
      "userInfo.nickName": e.detail.value
    })
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.showLoading({
      title: '',
    });
    let openId;
    let userinfo;
    // get openid
    openId = wx.getStorageSync('openId');
    if (!openId) { // 缓存没有，到后台拿
      openId = await this.getOpenId();
      if (!openId) return wx.hideLoading();
      wx.setStorage({
        key: 'openId',
        data: openId,
      });
    }
    this.setData({
      openId,
    });
    // get userinfo
    userinfo = wx.getStorageSync(openId);
    if (!userinfo) { // 缓存没有，通过云数据库拿, 未登录状态
      userinfo = await this.getUserInfo(openId);
      if (!userinfo) { // 未注册
        this.setData({
          hasRegister: false,
        });
      } else {
        this.setData({
          hasRegister: true,
        });
      }
    } else { // 缓存有，无须登录
      this.setData({
        hasRegister: true,
        hasLogin: true,
        userInfo: userinfo,
      });
    }
    wx.hideLoading();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  register(e) {
    wx.getUserProfile({
      desc: '获取你的用户信息',
      success: async (res) => {
        console.log(res);
        const { userInfo } = res;
        userInfo.cnt = 1;
        this.setData({
          userInfo,
        });
        wx.setStorage({
          key: this.data.openId,
          data: userInfo,
        });
        userInfo._id = this.data.openId;
        // this.getOpenId(e)
        await collection.add({
          data: userInfo,
        });
        this.setData({
          hasRegister: true,
          hasLogin: true,
        });
      },
      fail: () => {
        wx.showToast({
          title: '注册失败',
          duration: 2000,
        });
      },
    });
  },

  async login(e) {
    wx.getUserProfile({
      desc: '获取你的用户信息',
      success: async (res) => {
        let { userInfo } = res;
        await collection.doc(this.data.openId).update({
          data: {
            ...userInfo,
            cnt: _.inc(1),
          },
        });
        userInfo = await this.getUserInfo(this.data.openId);
        wx.setStorage({
          key: this.data.openId,
          data: userInfo,
        });
        this.setData({
          userInfo,
          hasLogin: true,
        });
      },
      fail: () => {
        wx.showToast({
          title: '注册失败',
          duration: 2000,
        });
      },
    });
  },

  async getOpenId() {
    wx.showLoading({
      title: '获取openid中',
    });
    return wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: app.globalData.selectedEnv.envId,
      },
      data: {
        type: 'getOpenId',
      },
    }).then((resp) => {
      this.setData({
        haveGetOpenId: true,
        openId: resp.result.openid,
      });
      wx.hideLoading();
      return resp.result.openid;
    })
      .catch((e) => {
        this.setData({
          showUploadTip: true,
        });
        wx.hideLoading();
      });
  },

  async createCollection() {
    wx.showLoading({
      title: '登录中',
    });
    return await wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: app.globalData.selectedEnv.envId,
      },
      data: {
        type: 'createUserInfoCollection',
        collection_name: 'userinfo',
      },
    });
  },

  logout(e) {
    this.setData({
      hasLogin: false,
      userInfo: {},
    });
    // clear storage
    wx.removeStorage({
      key: this.data.openId,
    });
  },

  clearOpenId() {
    this.setData({
      haveGetOpenId: false,
      openId: ''
    })
  },

  async getUserRiskRank() {
    const ret = await wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: app.globalData.selectedEnv.envId
      },
      data: {
        type: 'getUserRiskRank'
      }
    })
    if (ret.result) {
      const { errCode, riskRank, errMsg} = ret.result
      switch(errCode) {
        case 0:
          wx.showModal({
            title: '获取成功',
            content: `当前用户风险等级为【${riskRank}】`
          })
          break
        case 48001:
          wx.showModal({
            title: '无权限',
            content: '请到管理后台【开发→开发管理→安全中心→风险用户扫描】开通'
          })
          break
        case 61010:
          wx.showModal({
            title: '用户访问记录超时',
            content: '用户未在近两小时访问小程序'
          })
          break
        default:
          wx.showModal({
            title: `errCode[${errCode}]`,
            content: errMsg
          })
          break
      }
    }
    console.log("用户风险等级", ret)
  }
})
